package com.itheima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.itheima.pojo.AliyunOssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.InputStream;

@Component//启动的时候创建对象，放入ioc容器
@Slf4j
public class AliyunOssUtil {
    @Autowired
    private AliyunOssProperties aliyunOssProperties;

    public String upload(String fileName, InputStream is) {
        log.info("endpoint:{}",aliyunOssProperties.getEndpoint());
        log.info("accessKeyId:{}",aliyunOssProperties.getAccessKeyId());
        log.info("accessKeySecret:{}",aliyunOssProperties.getAccessKeySecret());
        log.info("bucketName:{}",aliyunOssProperties.getBucketName());

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliyunOssProperties.getEndpoint(), aliyunOssProperties.getAccessKeyId(), aliyunOssProperties.getAccessKeySecret());
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(aliyunOssProperties.getBucketName(), fileName, is);
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (Exception ce) {
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return "http://" + aliyunOssProperties.getBucketName() + "." + aliyunOssProperties.getEndpoint() + "/" + fileName;
    }
}
